package com.ganinfo.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ganinfo.common.Logger;
import com.ganinfo.common.data.TransmitMap;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.setting.Setting;

public class LogInterceptor implements HandlerInterceptor {
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	private final String env = new Setting("btsql-ext.properties").getStr("PRODUCT_MODE");//当前环境测试还是正式;
	/**
	 * controller执行后且视图返回后调用此方法
	 * 这里可得到执行controller时的异常信息
	 * 这里可记录操作日志，资源清理等
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
		if("false".equals(env)){//开发环境
			logger.info("--------------------"+DateUtil.now()+" 结束-------------------------------------");
			logger.info("");
		}
	}

	/**
	 * controller执行后但未返回视图前调用此方法
	 * 这里可在返回用户前对模型数据进行加工处理，比如这里加入公用信息以便页面显示
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {

	}

	/**
	 * controller执行前调用此方法
	 * 返回true表示继续执行，返回false中止执行
	 * 这里可以加入登录校验、权限拦截等
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
		//String url = request.getRequestURL().toString();
		if("false".equals(env)){//开发环境
			logger.info("");
			logger.info("--------------------"+DateUtil.now()+" 开始-------------------------------------");
			logger.info("ip地址:"+request.getRemoteAddr());
			logger.info("接口地址:"+request.getServletPath());
			logger.info("参数列表:"+new TransmitMap(request));
		}
//		if(!url.endsWith("loginmain")){
//			String token = request.getParameter("token");
//			IToken itoken = TokenFactory.getToken("redis", null);
//			boolean flag = itoken.validate(token);
//			if (!flag){//token失效
//				response.setContentType( "text/json;charset=UTF-8");
//				String result;
//				result = new Result(3, null, null, "登录超时，请重新登录！", null).toJson();
//				PrintWriter out = response.getWriter();
//			    out.write(result);
//			    out.close();
//			    return false; 
//			}
//		}
		return true;
	}

}
